﻿namespace com.crownpack
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web.Caching;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    using com.crownpack.Extensions.StringExtensions;

    using Microsoft.SharePoint;
    using Microsoft.SharePoint.WebControls;

    using ReferenceFieldValue = CustomerFieldValue;

    using ReferenceObject = Customer;

    public class CustomerFieldFieldControl : BaseFieldControl
    {
        #region Fields

        protected Label uiFull;
        protected DropDownList uiLocation;

        #endregion Fields

        #region Properties

        public override string DisplayTemplateName
        {
            get
            {
                return "CustomerFieldDisplayRenderingTemplate";
            }
            set
            {
                base.DisplayTemplateName = value;
            }
        }

        public ReferenceFieldValue InternalObj
        {
            get;
            set;
        }

        public override object Value
        {
            get
            {
                EnsureChildControls( );
                if ( ControlMode == SPControlMode.Edit || ControlMode == SPControlMode.New )
                {
                    validate( );

                    //setOtherFieldValues( );

                    ReferenceObject o = ReferenceObject.Deserialize( uiLocation.SelectedValue );

                    SPFieldMultiColumnValue mcv = new SPFieldMultiColumnValue( 3 );
                    mcv[ 0 ] = o.ParentCustomerNo.HasValue ? o.ParentCustomerNo.Value.ToString( ) : string.Empty;
                    mcv[ 1 ] = o.LocationNo.HasValue ? o.LocationNo.Value.ToString( ) : string.Empty;
                    //mcv[ 2 ] = uiLocation.SelectedValue.ToBase64String( );
                    mcv[ 2 ] = o.LocationName.HtmlEncode( );
                    ////SPFieldMultiColumnValue mcv = new SPFieldMultiColumnValue( 24 );
                    ////mcv[ Position.Address1 ] = o.Address1.HtmlEncode( );
                    ////mcv[ Position.Branch ] = o.Branch.HtmlEncode( );
                    ////mcv[ Position.BranchManager ] = o.BranchManager.HtmlEncode( );
                    ////mcv[ Position.BranchName ] = o.BranchName.HtmlEncode( );
                    ////mcv[ Position.City ] = o.City.HtmlEncode( );
                    ////mcv[ Position.DivisionCode ] = o.DivisionCode.HtmlEncode( );
                    ////mcv[ Position.GroupCode ] = o.GroupCode.HtmlEncode( );
                    ////mcv[ Position.LocationName ] = o.LocationName.HtmlEncode( );
                    ////mcv[ Position.LocationNo ] = o.LocationNo.HasValue ? o.LocationNo.Value.ToString( ) : string.Empty;
                    ////mcv[ Position.ManagerEMail ] = o.ManagerEMail.TryTrim( ).HtmlEncode( );
                    ////mcv[ Position.NA_ManagerEmailAddress ] = o.NA_ManagerEmailAddress.TryTrim( ).HtmlEncode( );
                    ////mcv[ Position.NA_ManagerName ] = o.NA_ManagerName.TryTrim( ).HtmlEncode( );
                    ////mcv[ Position.NA_ManagerNo ] = o.NA_ManagerNo.TryTrim( ).HtmlEncode( );
                    ////mcv[ Position.NA_ManagerPhone ] = o.NA_ManagerPhone.TryTrim( ).HtmlEncode( );
                    ////mcv[ Position.ParentCustomerName ] = o.ParentCustomerName.TryTrim( ).HtmlEncode( );
                    ////mcv[ Position.ParentCustomerNo ] = o.ParentCustomerNo.HasValue ? o.ParentCustomerNo.Value.ToString( ) : string.Empty;
                    ////mcv[ Position.Salesrep ] = o.Salesrep.TryTrim( ).HtmlEncode( );
                    ////mcv[ Position.SalesrepEmailAddress ] = o.SalesrepEmailAddress.TryTrim( ).HtmlEncode( );
                    ////mcv[ Position.SalesrepName ] = o.SalesrepName.TryTrim( ).HtmlEncode( );
                    ////mcv[ Position.SalesrepPhone ] = o.SalesrepPhone.TryTrim( ).HtmlEncode( );
                    ////mcv[ Position.SectorCode ] = o.SectorCode.TryTrim( ).HtmlEncode( );
                    ////mcv[ Position.St ] = o.St.TryTrim( ).HtmlEncode( );
                    ////mcv[ Position.Zip ] = o.Zip.TryTrim( ).HtmlEncode( );

                    return mcv;
                }
                else
                    return base.Value;
            }
            set
            {
                EnsureChildControls( );
                if ( ItemFieldValue == null )
                    return;

                SPFieldMultiColumnValue mcv = ( SPFieldMultiColumnValue ) ItemFieldValue;
                InternalObj = new ReferenceFieldValue( mcv );

                if ( ControlMode == SPControlMode.Edit || ControlMode == SPControlMode.New )
                {
                    int? index = null;
                    int i = 0;
                    foreach ( ListItem item in uiLocation.Items )
                    {
                        if ( !string.IsNullOrEmpty( item.Value ) )
                        {
                            ReferenceObject o = item.Value.HtmlDecode( ).DeserializeFromXml<ReferenceObject>( );
                            if ( o.ParentCustomerNo.HasValue && InternalObj.ParentCustomerNo.HasValue && o.ParentCustomerNo.Value == InternalObj.ParentCustomerNo.Value && o.LocationNo.HasValue && InternalObj.LocationNo.HasValue && o.LocationNo.Value == InternalObj.LocationNo.Value )
                            {
                                index = i;
                                break;
                            }
                        }
                        i++;
                    }
                    //uiLocation.SelectedIndex = uiLocation.Items.IndexOf( uiLocation.Items.FindByText( InternalObj.LocationName ) );
                    if ( index.HasValue )
                        uiLocation.SelectedIndex = index.Value;
                }
                else
                {
                    string s = InternalObj.GetHtmlFormat( );
                    if ( ControlMode == SPControlMode.Display )
                        uiFull.Text = s;
                }
                base.Value = value;
            }
        }

        protected override string DefaultTemplateName
        {
            get
            {
                if ( ControlMode == SPControlMode.Display )
                    return DisplayTemplateName;
                else
                    return "CustomerFieldDefaultRenderingTemplate";
            }
        }

        bool IsRequired
        {
            get
            {
                return SPContext.Current.Fields.GetField( this.FieldName ).Required;
            }
        }

        #endregion Properties

        #region Methods

        protected override void CreateChildControls( )
        {
            base.CreateChildControls( );
            if ( ControlMode == SPControlMode.Display )
            {
                uiFull = ( Label ) TemplateContainer.FindControl( "uiFull" );
            }
            else if ( ControlMode == SPControlMode.Edit || ControlMode == SPControlMode.New )
            {
                uiLocation = ( DropDownList ) TemplateContainer.FindControl( "uiLocation" );

                labelRequired( );
                uiLocation_LoadValues( );
            }
        }

        protected override void RenderFieldForDisplay( HtmlTextWriter output )
        {
            if ( ItemFieldValue == null )
            {
                output.Write( string.Empty );
                return;
            }
            SPFieldMultiColumnValue mcv = ( SPFieldMultiColumnValue ) ItemFieldValue;
            InternalObj = new ReferenceFieldValue( mcv );

            string s = InternalObj.GetHtmlFormat( );
            output.Write( s );
        }

        void labelRequired( )
        {
        }

        ////void setOtherFieldValues( )
        ////{
        ////    ReferenceObject o = ReferenceObject.Deserialize( uiLocation.SelectedValue );
        ////    SPListItem item = SPContext.Current.ListItem;
        ////    SPField[ ] fields = SPContext.Current.ListItem.Fields.Cast<SPField>( ).ToArray( );
        ////    item.Web.AllowUnsafeUpdates = true;
        ////    for ( int i = 0; i < fields.Count( ); i++ )
        ////    {
        ////        if ( fields[ i ].InternalName.Equals( Layout.LocationNo, StringComparison.OrdinalIgnoreCase ) )
        ////        {
        ////            fields[ i ].ParseAndSetValue( item, o.LocationNo.HasValue ? o.LocationNo.Value.ToString( ) : 0.ToString( ) );
        ////            var f=fields[ i ];
        ////            f.fieldv
        ////        }
        ////    }
        ////}
        void uiLocation_LoadValues( )
        {
            if ( uiLocation != null )
            {
                // get parent customer no
                int parentCustomerNo = 920010;

                List<ReferenceObject> l = ( List<ReferenceObject> ) Page.Cache.Get( parentCustomerNo.ToString( ) );
                if ( l == null || l.Count == 0 )
                {
                    LOBDao dao = new LOBDao( );
                    l = dao.GetByParentCustomerNo( parentCustomerNo );
                    Page.Cache.Add( parentCustomerNo.ToString( ),
                        l,
                        null,
                        Cache.NoAbsoluteExpiration,
                        new TimeSpan( 0, 15, 0 ), // 15 minutes
                        CacheItemPriority.Normal,
                        new CacheItemRemovedCallback(
                            delegate( string k, object v, CacheItemRemovedReason reason )
                            {
                            } ) );
                }

                uiLocation.Items.Add( string.Empty );
                foreach ( ReferenceObject o in l )
                    uiLocation.Items.Add( new ListItem( string.Format( "{0} - {1}, {2} {3}", o.LocationName, o.City, o.St, o.Zip ), o.Serialize( ) ) );
            }
        }

        void validate( )
        {
            if ( IsRequired )
            {
                bool ok = true;

                // validate
                if ( uiLocation.SelectedIndex == 0 )
                    ok = false;

                if ( !ok )
                    //throw new SPFieldValidationException( "You must specify a value for all required fields." );
                    throw new SPFieldValidationException( "You must specify a value for this required field." );
            }
        }

        #endregion Methods
    }
}